package com.lincoln.framework.interceptor;

import com.lincoln.framework.annotation.LoginBack;
import com.lincoln.framework.common.WebUtils;
import com.lincoln.framework.utils.FrameworkLogger;
import com.lincoln.framework.utils.ParameterChecker;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * <h1>登录返回拦截器</h1>
 * <p>
 * <p>
 * 用于方法需要登录，而未登录会员时，登录成功后跳转指定路径；LoginBack注解配套使用
 * </p>
 *
 * @author zwm
 */
public class LoginBackAuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 日志
     */
    private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(LoginBackAuthInterceptor.class);

    public static final String SESSION_LOGIN_BACK_URL = "session_login_back_url";

    /**
     * 登录返回拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        // 不需要登录，直接跳转
        if (WebUtils.getLoginMember() != null) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class clasz = handlerMethod.getBean().getClass();
        LoginBack loginBack = null;
        String controllerUrl = "";
        if (clasz.isAnnotationPresent(LoginBack.class)) {
            loginBack = (LoginBack) clasz.getAnnotation(LoginBack.class);
        }
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(LoginBack.class)) {
            loginBack = (LoginBack) method.getAnnotation(LoginBack.class);
        }
        if (loginBack == null) {
            return true;
        }

        String backUrl = "";
        if (loginBack.backRefererUrl()) {
            backUrl = request.getHeader("referer");
            backUrl = backUrl == null ? WebUtils.getRequestUrl() : backUrl;
        } else if (!ParameterChecker.isNullOrEmpty(loginBack.backUrl())) {
            backUrl = loginBack.backUrl();
        } else {
            backUrl = WebUtils.getRequestUrl();
        }
        if (backUrl.indexOf("isBack=1") == -1) {
            if (backUrl.indexOf("?") != -1) {
                backUrl += "&isBack=1";
            } else {
                backUrl += "?isBack=1";
            }
        }
        session.setAttribute(SESSION_LOGIN_BACK_URL, backUrl);
        if (!WebUtils.isAjaxRequest()) {
            response.sendRedirect(WebUtils.operateJsessionidOfUrl("http://" + request.getRemoteAddr() + "/login/toLogin.htm?needBack=1"));
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

}
